<template>
  <div>
    <div class="search-box">
      <el-date-picker v-model="dateList" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
        start-placeholder="开始日期" end-placeholder="结束日期">
      </el-date-picker>
      <!-- <el-select v-model="indicatrix" placeholder="请选择" style="margin-left: 16px">
        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
        </el-option>
      </el-select> -->
      <el-button type="primary" style="margin-left: 16px" @click="getChartData">查询</el-button>
    </div>
    <div id="map" style="width: 100%; height: calc(100vh - 60px)"></div>
    <div id="legend" style="
        display: flex;
        height: 200px;
        position: absolute;
        bottom: 10px;
        right: 10px;
        background-color: white;
        padding: 10px;
      ">
      <div id="legend-1" style="height: 180px"></div>
      <div id="legend-2" class="length-box2"></div>
    </div>
  </div>
</template>
<script>
  import {
    queryLegend,
    queryHospitalIndex,
    queryHospital,
  } from "@/api/atlas/index";

  import "ol/ol.css";
  import Map from "ol/Map.js";
  import View from "ol/View.js";
  import TileLayer from "ol/layer/Tile.js";
  import {
    fromLonLat
  } from "ol/proj";
  import OSM from "ol/source/OSM.js";
  import Feature from "ol/Feature.js";
  import Point from "ol/geom/Point";
  import Circle from "ol/geom/Circle";
  import {
    Style,
    Fill,
    Text,
    Stroke
  } from "ol/style";
  import VectorSource from "ol/source/Vector.js";
  import VectorLayer from "ol/layer/Vector.js";
  import {
    apiUrl
  } from "@/config/setting";
  import XYZ from "ol/source/XYZ.js";
  // import taiyuan from "./taiyuan.json";
  import kriging from "kriging.js";
  import ImageLayer from "ol/layer/Image.js";
  import ImageCanvas from "ol/source/ImageCanvas.js";
  import GeoJSON from "ol/format/GeoJSON.js";

  export default {
    data() {
      return {
        map: null,
        sourcePoint: null,
        dateList: [],
        indicatrix: "DNT", // DNT DRT  DPT
        options: [{
            value: "DNT",
            label: "DNT分布图",
          },
          {
            value: "DRT",
            label: "DRT分布图",
          },
          {
            value: "DPT",
            label: "DPT分布图",
          },
        ],
        hospitalList: [],
        levelList: [],
        hospitaColorlList: [],
        bianjie: [],
        range: 0,
      };
    },
    mounted() {
      // const bianjie = taiyuan.features[0].geometry.coordinates[0];
      // this.bianjie = [...bianjie];
      setTimeout(() => {
        let mapList = [];
        console.log("this.hospitaColorlList: ", this.hospitaColorlList);
        for (let i = 0; i < this.hospitaColorlList.length; i++) {
          const item = this.hospitaColorlList[i];
          const data = new VectorLayer({
            zIndex: 99,
            source: new VectorSource({
              features: [
                new Feature({
                  title: item.hospitalName,
                  geometry: new Point([item.lng - 0, item.lat - 0]),

                  // 设置点的样式
                }),
                // 0.09 是差不多10公里
                // 0.0009  差不多100m
                // 0.00099 差不多110m
                // 1米换算其实约等于 0.00001
                // 但是一般范围按10公里算， 这里乘个0.95 防止误差过大
                new Feature(
                  new Circle([item.lng - 0, item.lat - 0], this.range * 0.00001 * 0.95).transform(
                    "EPSG:4326",
                    "EPSG:3857"
                  )
                ),
              ],
            }),
            style: new Style({
              fill: new Fill({
                color: `rgba(${this.hexToRgb(item.color)},0.3)`,
              }),
              text: new Text({
                text: item.hospitalName,
                offsetY: 0,
                font: "12px Calibri,sans-serif",
                fill: new Fill({
                  color: "#333",
                  zIndex: 999,
                }),
                // stroke: new Stroke({
                //   color: "#000",
                //   width: 0,
                // }),
              }),
            }),
          });
          mapList.push(data);
        }
        console.log("mapList: ", mapList);
        setTimeout(() => {
          this.initMap(mapList);
          this.addGeoJson();
          this.drawKriging();
        });
      }, 2500);
    },
    created() {
      // this.getColorData();
      this.getHospitalLocation();
      this.getConfigKeyNoToken("sys.system.atlas.range").then((response) => {
        this.range = response.msg;
      });
    },
    methods: {
      getChartData() {
        this.map = null;
        this.hospitalList = [];
        this.levelList = [];
        this.hospitaColorlList = [];
        setTimeout(() => {
          this.getColorData();
          this.getHospitalLocation();
        })
        setTimeout(() => {
          this.initMap();
          // this.drawKriging();
        }, 1500);
      },
      // 十六进制颜色转rgb
      hexToRgb(hex) {
        console.log("hex: ", hex);
        if (!hex) {
          return "0,0,0";
        }
        // 移除前面的 '#' 字符
        hex = hex.replace(/^#/, "");

        // 如果是 3 位十六进制，转换为 6 位十六进制
        if (hex.length === 3) {
          hex = hex
            .split("")
            .map(function(item) {
              return item + item;
            })
            .join("");
        }

        // 解析 RGB 值
        var bigint = parseInt(hex, 16);
        var r = (bigint >> 16) & 255;
        var g = (bigint >> 8) & 255;
        var b = bigint & 255;

        return `${r}, ${g}, ${b}`;
      },
      // 根据指标查询图例信息
      getColorData() {
        const param = {
          name: this.indicatrix,
        };
        queryLegend(param).then((res) => {
          this.levelList = [...res.data];
        });
      },
      // 查询当前医院,并且返回经纬度
      getHospitalLocation() {
        const param = {
          areaCode: '',
          // startDate: "",
          // endDate: "",
        };
        queryHospital(param).then((res) => {
          this.hospitalList = [...res.data];
          this.hospitaColorlList = [];
        });
      },
      initMap(mapList) {
        // 初始化地图
        this.map = new Map({
          target: "map", // 地图容器的id
          layers: [
            new TileLayer({
              source: new XYZ({
                // 设置切片数据的URL模板，{z}表示缩放级别，{x}和{y}表示切片坐标
                url: 'http://101.201.226.21/gaode/{z}/{x}/{y}.png',
                // url: 'http://101.201.226.21/gaode/{z}/{x}/{y}.png',
                // url: apiUrl + "/profile/tiles_img_gaode_china_large/{z}/{x}/{y}.png",
                // 设置切片图层的归因信息
                // attributions: ['Your Tile Attribution Here']
              }),
            }),
            ...mapList,
          ],
          view: new View({
            center: fromLonLat([112.556197, 37.876857]), // 地图中心点坐标(太原市人民政府)
            zoom: 10, // 缩放级别
          }),
        });
      },
      drawKriging() {
        let params = {
          colors: this.levelList.map((item) => {
            return item.color;
          }),
        };
        // 获取用于显示图例的 <div> 元素
        let legendDiv = document.getElementById("legend-1");
        let legendDiv2 = document.getElementById("legend-2");
        // 遍历 colors 数组，为每个颜色创建一个色块并显示在图例中
        this.levelList.forEach((item, index) => {
          let colorBlock = document.createElement("div");
          colorBlock.style.width = "10px";
          colorBlock.style.height = `${100 / params.colors.length}%`;
          colorBlock.style.backgroundColor = item.color;
          legendDiv.appendChild(colorBlock);
          // if(index % 32 == 0) {
          let colorBlock2 = document.createElement("div");
          colorBlock2.style.textAlign = "center";
          colorBlock2.innerHTML = `${item.level}<br/>(${item.lower - 0}~${
          item.upper - 0 || ""
        })`;
          legendDiv2.appendChild(colorBlock2);
          // }
        });
        let colorBlock2 = document.createElement("div");
        colorBlock2.innerHTML = "";
        legendDiv2.appendChild(colorBlock2);
      },
      addGeoJson() {
        let json = require("./taiyuan-1.json");
        let features = new GeoJSON({
          featureProjection: "EPSG:3857",
        }).readFeatures(json);
        var vectorSource = new VectorSource({
          features: features,
        });
        let lineLayer = new VectorLayer({
          zIndex: 0,
          source: vectorSource,
          // style: this.createStyleFunction()
        });
        this.map.addLayer(lineLayer); // 把图层添加到地图
      },
    },
  };
</script>
<style scoped>
  .length-box2 {
    height: 180px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    margin-left: 4px;
  }

  .level-box {
    position: fixed;
    right: 24px;
    bottom: 24px;
  }

  .color-box {
    display: flex;
    align-items: center;
    /* margin-top: 8px; */
    font-size: 14px;
  }

  .color-div {
    height: 18px;
    width: 24px;
    margin: 0 16px;
  }

  .search-box {
    position: absolute;
    left: 30px;
    top: 0;
    width: 100%;
    height: 56px;
    padding-left: 16px;
    display: flex;
    align-items: center;
    z-index: 999;
  }
</style>
